package com.cat.slidingWindow;

import java.util.Arrays;

/**
 * @author cat
 * @description https://leetcode.cn/problems/longest-nice-subarray/
 * @create 2025/8/1 14:25
 * @since JDK17
 */

public class Solution26 {
    static int[] h = new int[32];
    boolean judge(int x) {
        for (int i = 0; x != 0; x /= 2, i++) {
            if (((x & 1) != 0) && h[i] > 1) {
                return true;
            }
        }
        return false;
    }

    void put(int x) {
        for (int i = 0; x != 0; x /= 2, i++) {
            if ((x & 1) != 0) { // 太贴心了
                h[i]++;
            }
        }
    }
    void remove(int x) {
        for (int i = 0; x != 0; x /= 2, i++) {
            if ((x & 1) != 0) { // 太贴心了
                h[i]--;
            }
        }
    }

    public int longestNiceSubarray(int[] nums) {
        Arrays.fill(h, 0);
        int ans = 1, n = nums.length;
        for (int l = 0, r = 0; r < n; r++) {
            put(nums[r]);
            while (judge(nums[r])) {    // 不合法
                remove(nums[l++]);
            }
            ans = Math.max(ans, r - l + 1);
        }
        return ans;
    }
}
